import React, { useState, useEffect, useRef } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { useInventory } from '../hooks/useInventory';
import { useUsers } from '../hooks/useUsers';
import { useStats } from '../hooks/useStats';
import { useActivity } from '../hooks/useActivity';
import { useAlerts } from '../hooks/useAlerts';
import { useAnalytics } from '../hooks/useAnalytics';
import { useSettings } from '../hooks/useSettings';
import { inventoryAPI, usersAPI, settingsAPI } from '../utils/api';
import { supabase } from '../config/supabase';
import AddItemModal from '../components/modals/AddItemModal';
import EditItemModal from '../components/modals/EditItemModal';
import AddUserModal from '../components/modals/AddUserModal';
import EditUserModal from '../components/modals/EditUserModal';
import ConfirmDeleteModal from '../components/modals/ConfirmDeleteModal';
import { 
  LogOut, 
  BarChart3, 
  Users as UsersIcon, 
  Package, 
  Settings, 
  TrendingUp, 
  AlertTriangle,
  Home,
  ChevronDown,
  Plus,
  Download,
  Bell,
  Search,
  Filter,
  Edit,
  Trash2,
  CheckCircle,
  PieChart,
  Upload,
  Loader2,
  User,
  Mail,
  Key,
  X
} from 'lucide-react';

const AdminDashboard: React.FC = () => {
  const { user, signOut } = useAuth();
  const { items: inventoryItems, categories, loading: inventoryLoading, refetch: refetchInventory } = useInventory();
  const { users: usersList, loading: usersLoading, refetch: refetchUsers } = useUsers();
  const { stats, loading: statsLoading, refetch: refetchStats } = useStats();
  const { activities, loading: activityLoading, refetch: refetchActivity } = useActivity();
  const { alerts: alertsList, loading: alertsLoading, refetch: refetchAlerts } = useAlerts();
  const { analytics, loading: analyticsLoading, refetch: refetchAnalytics } = useAnalytics();
  const { settings: pantrySettings, loading: settingsLoading, refetch: refetchSettings } = useSettings();
  
  // Track resolved alerts locally
  const [resolvedAlerts, setResolvedAlerts] = useState<Set<string>>(new Set());
  
  const [activeTab, setActiveTab] = useState('overview');
  const [showProfileMenu, setShowProfileMenu] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [userRoleFilter, setUserRoleFilter] = useState<'all' | 'user' | 'volunteer' | 'admin'>('all');
  const [showUserFilterMenu, setShowUserFilterMenu] = useState(false);
  
  // Inventory filters
  const [inventorySearchQuery, setInventorySearchQuery] = useState('');
  const [inventoryCategoryFilter, setInventoryCategoryFilter] = useState('all');
  const [inventoryStatusFilter, setInventoryStatusFilter] = useState<'all' | 'good' | 'fresh' | 'expiring' | 'low' | 'expired'>('all');
  const [showInventoryFilterMenu, setShowInventoryFilterMenu] = useState(false);
  
  // Modal states
  const [showAddItemModal, setShowAddItemModal] = useState(false);
  const [showEditItemModal, setShowEditItemModal] = useState(false);
  const [showAddUserModal, setShowAddUserModal] = useState(false);
  const [showEditUserModal, setShowEditUserModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showAccountSettings, setShowAccountSettings] = useState(false);
  const [selectedItem, setSelectedItem] = useState<any>(null);
  const [selectedUser, setSelectedUser] = useState<any>(null);
  const [deleteLoading, setDeleteLoading] = useState(false);
  
  // Account settings states
  const [editingEmail, setEditingEmail] = useState(false);
  const [newEmail, setNewEmail] = useState('');
  const [editingPassword, setEditingPassword] = useState(false);
  const [oldPassword, setOldPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [accountLoading, setAccountLoading] = useState(false);
  const [accountError, setAccountError] = useState('');

  // Settings form state
  const [settingsForm, setSettingsForm] = useState({
    pantryName: '',
    contactPhone: '',
    address: '',
  });
  const [settingsSaving, setSettingsSaving] = useState(false);
  const [settingsError, setSettingsError] = useState('');
  const [settingsSuccess, setSettingsSuccess] = useState(false);

  // Refs for click-outside detection
  const profileMenuRef = useRef<HTMLDivElement>(null);
  const userFilterMenuRef = useRef<HTMLDivElement>(null);
  const inventoryFilterMenuRef = useRef<HTMLDivElement>(null);

  // Close dropdowns when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (profileMenuRef.current && !profileMenuRef.current.contains(event.target as Node)) {
        setShowProfileMenu(false);
      }
      if (userFilterMenuRef.current && !userFilterMenuRef.current.contains(event.target as Node)) {
        setShowUserFilterMenu(false);
      }
      if (inventoryFilterMenuRef.current && !inventoryFilterMenuRef.current.contains(event.target as Node)) {
        setShowInventoryFilterMenu(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // Load settings into form when they're fetched
  useEffect(() => {
    if (pantrySettings) {
      setSettingsForm({
        pantryName: pantrySettings.pantryName || '',
        contactPhone: pantrySettings.contactPhone || '',
        address: pantrySettings.address || '',
      });
    }
  }, [pantrySettings]);

  const handleSignOut = async () => {
    await signOut();
  };

  // Refresh all data across tabs
  const refreshAllData = async () => {
    await Promise.all([
      refetchInventory(),
      refetchStats(),
      refetchActivity(),
      refetchAlerts(),
      refetchAnalytics()
    ]);
  };

  const tabs = [
    { id: 'overview', name: 'Overview', icon: Home },
    { id: 'analytics', name: 'Analytics', icon: BarChart3 },
    { id: 'users', name: 'Users', icon: UsersIcon },
    { id: 'inventory', name: 'Inventory', icon: Package },
    { id: 'alerts', name: 'Alerts', icon: AlertTriangle },
    { id: 'settings', name: 'Settings', icon: Settings },
  ];

  // Helper functions
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  };

  const getTimeAgo = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
    
    if (diffMins < 1) return 'Just now';
    if (diffMins < 60) return `${diffMins} min ago`;
    if (diffHours < 24) return `${diffHours} hour${diffHours !== 1 ? 's' : ''} ago`;
    if (diffDays < 7) return `${diffDays} day${diffDays !== 1 ? 's' : ''} ago`;
    return formatDate(dateString);
  };

  const getDaysUntilExpiry = (expiryDate?: string) => {
    if (!expiryDate) return null;
    const days = Math.ceil((new Date(expiryDate).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24));
    return days;
  };

  const getItemStatus = (item: any) => {
    const days = getDaysUntilExpiry(item.expiryDate);
    // Check expiry status first (higher priority than low stock)
    if (days !== null && days <= 0) return 'expired';
    if (days !== null && days <= 2) return 'expiring';
    if (days !== null && days <= 7) return 'fresh';
    // Then check low stock
    if (item.isLowStock) return 'low';
    return 'good';
  };

  // Handler functions for modals
  const handleEditItem = (item: any) => {
    setSelectedItem(item);

  const tabs = [
    { id: 'overview', name: 'Overview', icon: Home },
    { id: 'analytics', name: 'Analytics', icon: BarChart3 },
    { id: 'users', name: 'Users', icon: UsersIcon },
    { id: 'inventory', name: 'Inventory', icon: Package },
    { id: 'alerts', name: 'Alerts', icon: AlertTriangle },
    { id: 'settings', name: 'Settings', icon: Settings },
  ];

  // Helper functions
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  };

  const getTimeAgo = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
    
    if (diffMins < 1) return 'Just now';
    if (diffMins < 60) return `${diffMins} min ago`;
    if (diffHours < 24) return `${diffHours} hour${diffHours !== 1 ? 's' : ''} ago`;
    if (diffDays < 7) return `${diffDays} day${diffDays !== 1 ? 's' : ''} ago`;
    return formatDate(dateString);
  };

  const getDaysUntilExpiry = (expiryDate?: string) => {
    if (!expiryDate) return null;
    const days = Math.ceil((new Date(expiryDate).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24));
    return days;
  };

  const getItemStatus = (item: any) => {
    const days = getDaysUntilExpiry(item.expiryDate);
    // Check expiry status first (higher priority than low stock)
    if (days !== null && days <= 0) return 'expired';
    if (days !== null && days <= 2) return 'expiring';
    if (days !== null && days <= 7) return 'fresh';
    // Then check low stock
    if (item.isLowStock) return 'low';
    return 'good';
  };

  // Handler functions for modals
  const handleEditItem = (item: any) => {
